require("express-async-errors"); //捕获异步异常
const express = require("express");
const app = express();
const cors = require("cors");
const connectMongo = require("./plugins/mongo");
const startAdmin = require("./router/admin");
const startWeb = require("./router/web");
const startCommon = require("./router/common");
const bodyParser = require("body-parser");
const { resData } = require("./utils/format");
const session = require("express-session");
(async () => {
    await connectMongo();
    app.use(cors({ credentials: true, origin: true }));//credentials:配置cookie跨域，origin：配置允许跨域的域名（为true时没有域名限制）
    app.set("jwtSecret", "1472580963"); //设置全局变量，jwt密钥
    app.set("sessionSecret", "1472580963"); //设置全局变量，jwt密钥
    app.set("jwtExp", 60 * 60 * 12); //登录过期时间(秒)
    //extended:false 方法内部使用querystring模块处理请求参数的格式
    //extended:true 方法内部使用第三方模块qs处理请求参数的格式
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    app.use(
        session({
            secret: app.get("sessionSecret"),
            resave: false,
            cookie: {
                maxAge: 1000 * 60 * 60 * 24,
            },
        })
    );
    app.use("/doc", express.static(__dirname + "/public/apidoc"));
    app.use("/common/api/upload", express.static(__dirname + "/uploads"));
    startCommon(app);
    startAdmin(app);
    startWeb(app);
    // app.get("/doc", (req, res) => {
    //     res.send(resData({ admin: "/admin/api/rest", web: "/web/api/rest", models: ["Category", "Commodity"] }));
    // });
    //全局异常处理
    app.use((err, req, res, next) => {
        res.send(resData(err.data || null, { code: err.statusCode || 500, message: err.message, ...err }));
    });
    app.listen(3110, () => {
        console.log("http://localhost:3110");
    });
})();
